package com.example.common.service.impl;

import com.example.common.service.ICacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;

import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;

/**
 * 缓存管理service
 */

public class CaffeineCacheService implements ICacheService {
    @Autowired
    CacheManager cacheManager;

    @Override
    public Cache getCache(String name){
        return cacheManager.getCache(name);
    }

    /**
     * 描述 : <获得缓存名称集合>. <br>
     * <p>
     * <使用方法说明>
     * </p>
     *
     * @return
     */
    @Override
    public Iterator<String> getCacheNames() {
        Collection<String> cacheNames = cacheManager.getCacheNames();
        Iterator<String> iterator = cacheNames.iterator();
        return iterator;
    }

    @Override
    public ConcurrentMap<Object, Object> getNativeCache(String name){
        CaffeineCache cache = (CaffeineCache)getCache(name);
        return cache.getNativeCache().asMap();
    }

    @Override
    public boolean deleteByKey(String name, String key) {
        CaffeineCache cache = (CaffeineCache)getCache(name);
        cache.evict(key);
        return true;
    }
}
